<?php

m2import('cms/cmsPermission.o.inc.php');


class user {

  function user ($usr,&$dba) {
    $this->user = $usr;
    $this->dba = &$dba;
    $this->errorMsg = '';
    $this->getPermissions();
  }

/*-- protected --*/

    function getPermissions()
    {
        global $cfgPaths;
        m2import('dba/dbaPermission.o.inc.php');
        $perm = new dbaPermission($this->dba);
        //$this->usr['rights']['upm'] = $perm->getByUid($this->usr['data']['id']);
        if (isset($this->user['data']['id']))
        {
        	$this->user['rights']['upm'] = $perm->getByUid($this->user['data']['id']);
        	$tmp = $perm->getUserGroups($this->user['data']['id']);
        }
        if (isset($tmp) && is_array($tmp))
        {
            foreach($tmp As $n => $v)
            {
                if (isset($this->user['rights']['upm'][$n]) && is_array($this->user['rights']['upm'][$n]))
                {
                    if ($v['v']=='Y') $this->user['rights']['upm'][$n]['v'] = 'Y';
                    if ($v['u']=='Y') $this->user['rights']['upm'][$n]['u'] = 'Y';
                    if ($v['d']=='Y') $this->user['rights']['upm'][$n]['d'] = 'Y';
                    if ($v['p']=='Y') $this->user['rights']['upm'][$n]['p'] = 'Y';
                    if ($v['a']=='Y') $this->user['rights']['upm'][$n]['a'] = 'Y';
                }
                else
                {
                    $rights = array('v' => $v['v'],'u' => $v['u'],'d' => $v['d'],'p' => $v['p'],'a' => $v['a']);
                    $this->user['rights']['upm'][$n] = $rights;
                }
            }
        }
//        var_dump($this->usr['rights']['menu']);
        unset($tmp);        
        unset($perm);        
    }

  // get UserData from DB
  function fetchUserData ($name,$pwd) {
    $sth  = $this->dba->query("select * from ".$this->dba->tableforwarder."_User where name=".$this->dba->quote($name)." AND pwd=".$this->dba->quote($pwd)." AND type='user' AND xics_login='Y';");
    if (is_object($sth))
      return $sth->fetch_row_Array();
  }

  // get UserData from DB
  function getMenus ($user_id) {
    $sth  = $this->dba->query("select * from ".$this->dba->tableforwarder."_User,".$this->dba->tableforwarder."_GroupUser where ".$this->dba->tableforwarder."_User.id=".$this->dba->tableforwarder."_GroupUser.group_id and user_id=$user_id;");
    if (is_object($sth))
    {
      $rows = $sth->fetch_rows_Array();
      $res  = array();
      for ($i=0;$i<count($rows);$i++)
      {
      	$res[] = $rows[$i]['menusettings'];
      }
      return $res;
    }
  }

  // check matching of user and pwd, if true store userdata
    function checkAndStoreUser ($name,$pwd) {
        $user = $this->fetchUserData($name,$pwd);
        if ($user){
            $this->user['data'] = $user;
            $this->user['authenticated']  = true;
            $menus	 	     = $this->getMenus($user['id']);
            $menus[]			 = $user['menusettings']; 
            $visibleitems		 = array();
            for ($i=0;$i<count($menus);$i++)
            {
                $menarr = explode(';',$menus[$i]);
                for ($j=0;$j<count($menarr);$j++)
                {
                    if (!in_array($menarr[$j],$visibleitems))
                        $visibleitems[] = $menarr[$j];
                }
            }
            $this->user['rights']['menu'] = $visibleitems;
            return true;
        } else {
            $this->loginError('User und/oder Passwort falsch!');
        }
    }

  // set user state to online
  function setOnline(){
    global $cfgPaths;
      // user auf online setzen
    include_once($cfgPaths['lib/dba'].'dbaOnlineUser.o.inc.php');
    $onu = new dbaOnlineUser($this->dba);
    if ($onu->check($this->user['data']['id']))
      $onu->update($this->user['data']['id']);
    else
      $onu->add($this->user['data']['id'],$this->user['data']['name'],$this->user['data']['long_name']);
    $this->onu = $onu;
    
  }

  // set user state to online
  function setOffline(){
    global $cfgPaths;
      // user auf online setzen
    include_once($cfgPaths['lib/dba'].'dbaOnlineUser.o.inc.php');
    $onu = new dbaOnlineUser($this->dba);
    $onu->del($this->user['data']['id']);
  }

  // login handling error
  function loginError ($msg) {
    $this->errorMsg = $msg;
    $this->user['authenticated'] = false;
  }

  // display login form
  function sendLogin () {
    global $cfgPaths,$cfgAdminIndex;
    $name  = $this->user['data']['name'];
    $error = $this->errorMsg;
    include($cfgPaths['lib/admin'].'login.html');
    //exit;
  }

  // display logout
  function sendLogout () {
    global $cfgPaths,$cfgAdminIndex;
    include($cfgPaths['lib/admin'].'logout.html');
    //exit;
  }

/*-- public --*/

  // check whether usr is authenticated or force authentication
  function authenticate ($name='',$pass='') {
    if (SID)
    {
        $env = & env::getInstance();
        $env->setAttribute('cookie_msg', 'Cookies m&uuml;ssen aktiviert sein! Vorsicht: Manche Browser sollten nach dem Aktivieren neu gestartet werden.');
        $this->sendLogin();
    }
    if (!$this->user['authenticated']){
     if ($name && $pass){
       if (!$this->checkAndStoreUser($name,$pass))
         $this->sendLogin();
     } else {
       $this->sendLogin();
     }
    } else {
      $this->setOnline();
    }
  }

  // admin menu array preparation
  function prepareAdminMenu (&$mar) {
    if ($this->user['data']['name']=='admin' || ((!xicsEdition(PRO_EDITION)) && $this->user['data']['name']=='superuser'))
    {
        $menu = $mar;
    } else {
     for ($i=0;$i<count($mar);$i++){
      if (is_array($this->user['rights']['menu']) && in_array($mar[$i]['id'],$this->user['rights']['menu'])){
        $menu[] = $mar[$i];
      }
     }
    } # else
    return $menu;
  }

  function exportUserData(){
    return $this->user;
  }

  function isAuthenticated(){
    return (isset($this->user['authenticated']) && $this->user['authenticated']);
  }

  function checkPermission($pmslot,$right){
    if ($this->user['data']['name']=='admin')
        return true; 
    if ($this->user['data']['name']=='superuser' && (!xicsEdition(PRO_EDITION)))
        return true;
    return (isset($this->user['rights']['upm'][$pmslot]) 
    		&& isset($this->user['rights']['upm'][$pmslot][$right]) 
    		&& $this->user['rights']['upm'][$pmslot][$right] == 'Y')?true:false;
  }
  
  function getDocumentPermissions($doc_id) {
      $ctx = & base_ApplicationContext::getInstance();
      $ldba   = $ctx->accessFactory->getInstanceOf('CMSLang');
      $check  = $ldba->getLanguages($langtable,true);
      $dba    = $ctx->accessFactory->getInstanceOf('CMS', $langtable);
      return new cmsPermission($dba->getUserPermissions($doc_id,$this->user['data']['id']));      
  }

  function logout () {
    $this->setOffline();
  	if ($GLOBALS['env']->getCookie(session_name())) {
        setcookie(session_name(), '', time()-42000, '/');
    }
    session_destroy();
    $this->sendLogout();
  }

}

?>